package com.firewolf.vue.service.impl;

import com.firewolf.vue.mapper.RoleMapper;
import com.firewolf.vue.mapper.RoleMenuMapper;
import com.firewolf.vue.params.RoleParam;
import com.firewolf.vue.pojo.Role;
import com.firewolf.vue.pojo.RoleMenu;
import com.firewolf.vue.pojo.RoleMenuExample;
import com.firewolf.vue.pojo.User;
import com.firewolf.vue.service.RoleService;
import com.firewolf.vue.vo.PageVo;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 作者：刘兴
 * 时间:19/3/1
 **/
@Service
@Slf4j
public class RoleServiceImpl implements RoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    @Override
    public List<Role> getAllRoles() {
        log.info("开始查询所有的角色");
        return roleMapper.selectByExample(null);
    }

    @Override
    public PageVo<Role> findList(RoleParam param) {
        PageHelper.startPage(param.getCpage(), param.getPageSize());

        List<Role> uList = roleMapper.findByParams(param);

        PageInfo<Role> pageInfo = new PageInfo<>(uList);
        PageVo<Role> vo = new PageVo<>(pageInfo.getTotal(), pageInfo.getList());
        return vo;

    }

    @Override
    public List<Long> findMenuIds(Long roleId) {

        RoleMenuExample rme = new RoleMenuExample();
        rme.createCriteria().andRoleIdEqualTo(roleId);
//        List<Long> ids = new ArrayList<>();
//        roleMenuMapper.selectByExample(rme).stream().forEach(x -> ids.add(x.getMenuId()));
        List<Long> ids = roleMenuMapper.selectLeafMenuIdsByRoleId(roleId);
        return ids;
    }

    @Override
    public void updaterolemenus(Long roleid, String menuids) {
        RoleMenuExample rme = new RoleMenuExample();
        rme.createCriteria().andRoleIdEqualTo(roleid);
        roleMenuMapper.deleteByExample(rme);
        if (menuids != null && menuids.length() > 0) {
            for (String menuid : menuids.split(",")) {
                RoleMenu rm = new RoleMenu();
                rm.setMenuId(Long.parseLong(menuid));
                rm.setRoleId(roleid);
                rm.setCreateTime(new Date());
                roleMenuMapper.insert(rm);
            }
        }
    }
}



